#include "mainwindow.h"
#include <QWidget>
#include <QListWidgetItem>
#include <QIcon>
#include <QSize>
#include <QMessageBox>
#include <QFileDialog>
#include <QRandomGenerator>
#include <QApplication>
#include <QPalette>
#include <QBrush>
#include <QColor>
#include <QDebug>
#include <QPainter>
#include <QResizeEvent> // 添加头文件
#include <QAudioDeviceInfo>
#include <QSound>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , m_currentScene(0) // 添加当前场景标记
    , m_showingCombo(false) // 初始化合成图显示状态
    , m_currentComboPath("") //当前合成图路径
    ,m_sceneItem(nullptr)
    ,m_upcloItem(nullptr)
    ,m_downcloItem(nullptr)
    ,m_dressItem(nullptr)
    ,m_shoesItem(nullptr)

    , m_bgmPlayer(nullptr)
    , m_bgmEnabled(false) // 默认开启BGM
    , m_bgmPath(":/bgm/materialPackage/bgm/happy.wav") // BGM资源路径
    , m_characterItem(nullptr)
    , m_comboItem(nullptr)  // 初始化合成图项

{
    setWindowTitle("服饰搭配工具");
    setMinimumSize(1000,700);

    initUI();
    initConnections();
    loadClothes();
    loadOutfitCombos(); // 加载套装组合
    onScene1BtnClicked(); //只设置背景，不加载人物
    loadCharacter(); //只在初始化时加载一次人物

    checkAudioDevices(); // 添加这行

    if (m_bgmToggleBtn)
    {
      m_bgmToggleBtn->setText("开启BGM");
    }
    if (m_volumeSlider)
    {
        m_volumeSlider->setValue(50);
    }
}

MainWindow::~MainWindow()
{

    // 释放BGM资源
       if (m_bgmPlayer) {
           m_bgmPlayer->stop();
           delete m_bgmPlayer;
           m_bgmPlayer = nullptr; // 重要：设置为nullptr避免野指针
       }
}

void MainWindow::checkAudioDevices()
{
    QAudioDeviceInfo defaultDevice = QAudioDeviceInfo::defaultOutputDevice();
    qDebug() << "默认音频设备:" << defaultDevice.deviceName();

    if (defaultDevice.isNull()) {
        qWarning() << "没有可用的音频输出设备!";
        QMessageBox::warning(this, "音频错误", "未检测到音频输出设备，请检查系统音频设置");
    } else {
        qDebug() << "支持的编解码器:" << defaultDevice.supportedCodecs();
    }
}


// 初始化BGM
void MainWindow::initBGM()
{

    // 添加详细的调试信息
       qDebug() << "初始化BGM，文件路径:" << m_bgmPath;

       // 检查资源文件是否存在
       QFile file(m_bgmPath);
       if (!file.exists()) {
           qWarning() << "BGM文件不存在:" << m_bgmPath;
           // 尝试列出所有可用的资源
           qDebug() << "可用资源:" << QDir(":/").entryList();
           m_bgmEnabled = false;
           return;
       } else {
           qDebug() << "BGM文件存在，大小:" << file.size() << "字节";
       }

       // 创建媒体播放器
       m_bgmPlayer = new QMediaPlayer(this);

       // 添加详细的信号连接
       connect(m_bgmPlayer, &QMediaPlayer::stateChanged, [](QMediaPlayer::State state) {
           qDebug() << "BGM播放器状态:" << state;
       });

       connect(m_bgmPlayer, &QMediaPlayer::mediaStatusChanged, [](QMediaPlayer::MediaStatus status) {
           qDebug() << "BGM媒体状态:" << status;
       });

       connect(m_bgmPlayer, QOverload<QMediaPlayer::Error>::of(&QMediaPlayer::error),
               [](QMediaPlayer::Error error) {
           qWarning() << "BGM播放错误:" << error;
       });

       // 设置媒体源
       m_bgmPlayer->setMedia(QUrl(m_bgmPath));
       qDebug() << "媒体源已设置";

       // 设置音量
       m_bgmPlayer->setVolume(m_volumeSlider ? m_volumeSlider->value() : 50);
       qDebug() << "音量设置为:" << m_bgmPlayer->volume();

       // 开始播放
       if (m_bgmEnabled) {
           m_bgmPlayer->play();
           qDebug() << "开始播放BGM";
       }
}

// BGM开关切换
void MainWindow::toggleBGM()
{
    m_bgmEnabled = !m_bgmEnabled;
      qDebug() << "切换BGM状态，新状态:" << m_bgmEnabled;

      if (m_bgmEnabled)
      {
          if (!m_bgmPlayer)
          {
              qDebug() << "首次初始化BGM";
              initBGM();
          }
          else
          {
              qDebug() << "恢复播放BGM";
              m_bgmPlayer->play();
          }

          if (m_bgmToggleBtn)
          {
              m_bgmToggleBtn->setText("关闭BGM");
          }
      }
      else
      {
          if (m_bgmPlayer)
          {
              qDebug() << "暂停BGM";
              m_bgmPlayer->pause();
          }
          if (m_bgmToggleBtn)
          {
              m_bgmToggleBtn->setText("开启BGM");
          }
      }
}

// 设置音量
void MainWindow::setVolume(int volume)
{
    if (m_bgmPlayer)
    {
            m_bgmPlayer->setVolume(volume);
            qDebug() << "设置音量:" << volume;

        // 更新音量标签
        if (m_volumeLabel)
        {
            m_volumeLabel->setText(QString("音量: %1%").arg(volume));
        }
     }
        else
    {
            qDebug() << "BGM播放器未初始化，无法设置音量";
    }
}

void MainWindow::initUI()
{

    m_loadingLabel = new QLabel("就绪");
    m_loadingLabel->setStyleSheet("color: black; background: transparent; font-size: 10px;");

    setStyleSheet("background-image: url(:/scene/materialPackage/scene/roomscene.png); background-position: center; background-size: cover;");

    QWidget *centralWidget = new QWidget(this);
    QHBoxLayout *mainLayout = new QHBoxLayout(centralWidget);
    setCentralWidget(centralWidget);

    // 设置中央控件为完全透明，让背景完全可见
    centralWidget->setStyleSheet("background-color: rgba(255, 255, 255, 0);");

    //左侧标签页 - 设置为透明
    QTabWidget* tabWidget = new QTabWidget;
    tabWidget->setStyleSheet("QTabWidget::pane { border: 0; background-color: rgba(255, 255, 255, 50); } "
                            "QTabWidget::tab-bar { alignment: center; } "
                            "QTabBar::tab { background-color: rgba(255, 255, 255, 100); color: black; } "
                            "QTabBar::tab:selected { background-color: rgba(255, 255, 255, 150); }");

    m_upcloList = new QListWidget;
    m_upcloList->setViewMode(QListWidget::IconMode);
    m_upcloList->setIconSize(QSize(80,80));
    m_upcloList->setResizeMode(QListWidget::Adjust);
    m_upcloList->setSpacing(10);
    m_upcloList->setStyleSheet("background-color: rgba(255, 255, 255, 50); border: 1px solid rgba(255, 255, 255, 100);");
    tabWidget->addTab(m_upcloList,"上衣");

    m_downcloList = new QListWidget;
    m_downcloList->setViewMode(QListWidget::IconMode);
    m_downcloList->setIconSize(QSize(80, 80));
    m_downcloList->setResizeMode(QListWidget::Adjust);
    m_downcloList->setSpacing(10);
    m_downcloList->setStyleSheet("background-color: rgba(255, 255, 255, 50); border: 1px solid rgba(255, 255, 255, 100);");
    tabWidget->addTab(m_downcloList, "下装");

    m_shoesList = new QListWidget;
    m_shoesList->setViewMode(QListWidget::IconMode);
    m_shoesList->setIconSize(QSize(80, 80));
    m_shoesList->setResizeMode(QListWidget::Adjust);
    m_shoesList->setSpacing(10);
    m_shoesList->setStyleSheet("background-color: rgba(255, 255, 255, 50); border: 1px solid rgba(255, 255, 255, 100);");
    tabWidget->addTab(m_shoesList, "鞋子");

    m_dressList = new QListWidget;
    m_dressList->setViewMode(QListWidget::IconMode);
    m_dressList->setIconSize(QSize(80, 80));
    m_dressList->setResizeMode(QListWidget::Adjust);
    m_dressList->setSpacing(10);
    m_dressList->setStyleSheet("background-color: rgba(255, 255, 255, 50); border: 1px solid rgba(255, 255, 255, 100);");
    tabWidget->addTab(m_dressList, "连衣裙");

    mainLayout->addWidget(tabWidget,1);

    //中间展示区
    m_view = new QGraphicsView;
    m_scene = new QGraphicsScene;
    m_scene->setSceneRect(0,0,700,700);
    m_view->setScene(m_scene);
    m_view->setMinimumSize(410, 510);

    // 设置视图背景为透明
    m_view->setBackgroundBrush(Qt::transparent);
    m_view->setStyleSheet("background: transparent; border: 1px solid rgba(255, 255, 255, 100);");

    // 确保视图正确显示整个场景
    m_view->setSceneRect(m_scene->sceneRect());
    m_view->fitInView(m_scene->sceneRect(), Qt::KeepAspectRatio);

    m_view->setResizeAnchor(QGraphicsView::AnchorViewCenter);
    m_view->setMinimumSize(410,510);

    // 调整视图交互模式，确保能选中和拖拽物品
    m_view->setDragMode(QGraphicsView::RubberBandDrag);
    m_view->setMouseTracking(true);
    m_view->setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
    m_view->setRenderHint(QPainter::Antialiasing);

    mainLayout->addWidget(m_view,2);

    //右侧功能区 - 设置为透明
    QWidget* rightWidget = new QWidget;
    QVBoxLayout *rightLayout = new QVBoxLayout(rightWidget);
    rightLayout->setSpacing(20);
    rightWidget->setStyleSheet("background-color: rgba(255, 255, 255, 50); border: 1px solid rgba(255, 255, 255, 100);");

    m_scene1Btn = new QPushButton("房间");
    m_scene2Btn = new QPushButton("教室");
    m_saveBtn = new QPushButton("保存");
    m_resetBtn = new QPushButton("重置");
    m_randomBtn = new QPushButton("随机");
    m_themeCheckBox = new QCheckBox("深色主题");
    m_confirmBtn = new QPushButton("确认搭配");

    // BGM控制控件
        m_bgmToggleBtn = new QPushButton("关闭BGM");
        m_volumeSlider = new QSlider(Qt::Horizontal);
        m_volumeLabel = new QLabel("音量: 50%");

    // 设置按钮样式为半透明
    QString buttonStyle = "QPushButton { background-color: rgba(255, 255, 255, 150); border: 1px solid rgba(255, 255, 255, 200); padding: 8px; } "
                         "QPushButton:hover { background-color: rgba(255, 255, 255, 200); }";

    m_scene1Btn->setStyleSheet(buttonStyle);
    m_scene2Btn->setStyleSheet(buttonStyle);
    m_saveBtn->setStyleSheet(buttonStyle);
    m_resetBtn->setStyleSheet(buttonStyle);
    m_randomBtn->setStyleSheet(buttonStyle);
    m_confirmBtn->setStyleSheet(buttonStyle);
    m_bgmToggleBtn->setStyleSheet(buttonStyle);
    // 设置滑块样式
        m_volumeSlider->setStyleSheet(
            "QSlider::groove:horizontal {"
            "    border: 1px solid rgba(255, 255, 255, 100);"
            "    height: 8px;"
            "    background: rgba(255, 255, 255, 50);"
            "    margin: 0px;"
            "    border-radius: 4px;"
            "}"
            "QSlider::handle:horizontal {"
            "    background: rgba(255, 255, 255, 200);"
            "    border: 1px solid rgba(255, 255, 255, 150);"
            "    width: 18px;"
            "    margin: -5px 0;"
            "    border-radius: 9px;"
            "}"
            "QSlider::handle:horizontal:hover {"
            "    background: rgba(255, 255, 255, 255);"
            "}"
        );

        // 设置标签样式
        m_volumeLabel->setStyleSheet("color: black; background: transparent;");


        // 添加BGM控制到界面
        rightLayout->addWidget(new QLabel("背景音乐控制"));
        rightLayout->addWidget(m_bgmToggleBtn);
        rightLayout->addWidget(m_volumeLabel);
        rightLayout->addWidget(m_volumeSlider);

       rightLayout->addWidget(m_confirmBtn);
       rightLayout->addWidget(m_scene1Btn);
       rightLayout->addWidget(m_scene2Btn);
       rightLayout->addWidget(m_saveBtn);
       rightLayout->addWidget(m_resetBtn);
       rightLayout->addWidget(m_randomBtn);
       rightLayout->addWidget(m_themeCheckBox);
       rightLayout->addStretch();
       rightLayout->addWidget(m_loadingLabel);
    mainLayout->addWidget(rightWidget, 1);
}
// 更新背景图片
void MainWindow::updateBackground()
{
    QString backgroundPath;
    if (m_currentScene == 1)
    {
        backgroundPath = ":/scene/materialPackage/scene/roomscene.png";
    }
    else
    {
        backgroundPath = ":/scene/materialPackage/scene/schoolscene.png";
    }

    // 创建自适应背景的样式表
    QString style = QString(
        "QMainWindow {"
        "   background-image: url(%1);"
        "   background-position: center;"
        "   background-repeat: no-repeat;"
        "   background-size: cover;"
        "}"
    ).arg(backgroundPath);

    setStyleSheet(style);
}

void MainWindow::resizeEvent(QResizeEvent *event)
{
    QMainWindow::resizeEvent(event);

    updateBackground(); // 窗口大小变化时更新背景

    // 窗口大小变化时重新调整人物和服饰的缩放
     adjustCharacterAndClothesScale();
}

// 根据窗口大小调整人物和服饰的缩放
void MainWindow::adjustCharacterAndClothesScale()
{
    if (!m_characterItem) return;

    // 根据窗口大小计算新的缩放比例
    QSize windowSize = size();
    qreal scaleFactor = qMin(windowSize.width() / 1000.0, windowSize.height() / 700.0);
    scaleFactor = qBound(0.5, scaleFactor, 2.0); // 限制缩放范围

    // 更新人物
    QPixmap characterPixmap(m_characterPath);
    if (!characterPixmap.isNull())
    {
        QSize scaledSize = characterPixmap.size() * scaleFactor * 0.25;
        m_characterItem->setPixmap(
            characterPixmap.scaled(scaledSize, Qt::KeepAspectRatio, Qt::SmoothTransformation)
        );

        // 重新居中人物
        centerCharacter();
    }

    // 更新已加载的服饰
    updateClothesScale(scaleFactor);

    //更新合成图（自适应窗口大小）
    if(m_showingCombo && m_comboItem &&!m_currentComboPath.isEmpty())
    {
        updateComboScale(scaleFactor);
    }
}

// 居中人物靠下一点点
void MainWindow::centerCharacter()
{
    if (!m_characterItem || !m_view) return;

    QRectF viewRect = m_view->mapToScene(m_view->viewport()->rect()).boundingRect();
    QRectF characterRect = m_characterItem->boundingRect();

    QPointF centerPos(
        viewRect.center().x() - characterRect.width() / 2,
        viewRect.center().y() - characterRect.height() / 2+180
    );

    m_characterItem->setPos(centerPos);

    // 同时更新已穿戴服饰的位置
    updateClothesPosition();
}

// 更新服饰缩放
void MainWindow::updateClothesScale(qreal scaleFactor)
{
    qreal clothesScale = scaleFactor * 0.23;

    auto updateItem = [&](DragablePixmapItem* item, const QString& path)
    {
        if (!item) return;

        QPixmap pixmap(path);
        if (!pixmap.isNull())
        {
            QSize scaledSize = pixmap.size() * clothesScale;
            item->setPixmap(pixmap.scaled(scaledSize, Qt::KeepAspectRatio, Qt::SmoothTransformation));
        }
    };

    if (m_upcloItem)
    {
        ClothesInfo info = getClothesInfoByItem(m_upcloItem);
        updateItem(m_upcloItem, info.path);
    }
    if (m_downcloItem)
    {
        ClothesInfo info = getClothesInfoByItem(m_downcloItem);
        updateItem(m_downcloItem, info.path);
    }
    if (m_dressItem)
    {
        ClothesInfo info = getClothesInfoByItem(m_dressItem);
        updateItem(m_dressItem, info.path);
    }
    if (m_shoesItem)
    {
        ClothesInfo info = getClothesInfoByItem(m_shoesItem);
        updateItem(m_shoesItem, info.path);
    }
}

//新增函数，更新合成图缩放
void MainWindow::updateComboScale(qreal scaleFactor)
{
    if(!m_comboItem || m_currentComboPath.isEmpty())
    {
        return;
    }
    QPixmap pixmap(m_currentComboPath);

    if(!pixmap.isNull())
    {
        QSize scaledSize = pixmap.size() * scaleFactor * 0.26;
        m_comboItem->setPixmap(
                    pixmap.scaled(scaledSize,Qt::KeepAspectRatio, Qt::SmoothTransformation)
                    );
        if(m_characterItem)
        {
            m_comboItem->setPos(m_characterItem->pos());
        }
    }

}

// 更新服饰位置
void MainWindow::updateClothesPosition()
{
    if (!m_characterItem) return;

    auto updateItemPosition = [&](DragablePixmapItem* item, const QPoint& wearOffset) {
        if (item && item->isWorn())
        {
            QPointF characterPos = m_characterItem->pos();
            item->setPos(characterPos + wearOffset);
        }
    };

    if (m_upcloItem)
    {
        ClothesInfo info = getClothesInfoByItem(m_upcloItem);
        updateItemPosition(m_upcloItem, info.wearOffset);
    }
    if (m_downcloItem)
    {
        ClothesInfo info = getClothesInfoByItem(m_downcloItem);
        updateItemPosition(m_downcloItem, info.wearOffset);
    }
    if (m_dressItem)
    {
        ClothesInfo info = getClothesInfoByItem(m_dressItem);
        updateItemPosition(m_dressItem, info.wearOffset);
    }
    if (m_shoesItem)
    {
        ClothesInfo info = getClothesInfoByItem(m_shoesItem);
        updateItemPosition(m_shoesItem, info.wearOffset);
    }
}

void MainWindow::initConnections()
{
    connect(m_upcloList, &QListWidget::itemClicked, this, &MainWindow::onUpListItemClicked);
    connect(m_downcloList, &QListWidget::itemClicked, this, &MainWindow::onDownListItemClicked);
    connect(m_shoesList, &QListWidget::itemClicked, this, &MainWindow::onShoesListItemClicked);
    connect(m_dressList, &QListWidget::itemClicked, this, &MainWindow::onDressListItemClicked);

    connect(m_scene1Btn,&QPushButton::clicked,this,&MainWindow::onScene1BtnClicked);
    connect(m_scene2Btn,&QPushButton::clicked,this,&MainWindow::onScene2BtnClicked);
    connect(m_saveBtn,&QPushButton::clicked,this,&MainWindow::onSaveBtnClicked);
    connect(m_resetBtn, &QPushButton::clicked, this, &MainWindow::onResetBtnClicked);
    connect(m_randomBtn, &QPushButton::clicked, this, &MainWindow::onRandomBtnClicked);
    connect(m_themeCheckBox,&QCheckBox::toggled,this,&MainWindow::onThemeCheckBoxToggled);
    connect(m_confirmBtn, &QPushButton::clicked, this, &MainWindow::onConfirmBtnClicked);

    // BGM相关连接
    connect(m_bgmToggleBtn, &QPushButton::clicked, this, &MainWindow::onBgmToggleBtnClicked);
    connect(m_volumeSlider, &QSlider::valueChanged, this, &MainWindow::onVolumeChanged);

}

void MainWindow::loadClothes()
{
    // 添加上衣（wearOffset：对齐人物上半身）
        m_clothesList.append({
            "白色T恤",
            ":/upclothes/materialPackage/upclothes/T-shirt1.png",
            "上衣",
            QPoint(0, -30),    // 拖拽时临时偏移
            QPoint(0, -50)     // 穿戴时对齐偏移（需根据实际图片调整）
        });
        m_clothesList.append({
            "蓝色T恤",
            ":/upclothes/materialPackage/upclothes/T-shirt2.png",
            "上衣",
            QPoint(0, -30),
            QPoint(0, -50)
        });
        m_clothesList.append({
            "粉色T恤",
            ":/upclothes/materialPackage/upclothes/T-shirt3.png",
            "上衣",
            QPoint(0, -30),
            QPoint(0, -50)
        });
        m_clothesList.append({
            "黄色T恤",
            ":/upclothes/materialPackage/upclothes/T-shirt4.png",
            "上衣",
            QPoint(0, -30),
            QPoint(0, -50)
        });
        m_clothesList.append({
            "牛仔外套",
            ":/upclothes/materialPackage/upclothes/jacket.png",
            "上衣",
            QPoint(0, -30),
            QPoint(0, -60)     // 外套可能需要更大的偏移
        });

        // 添加下装（wearOffset：对齐人物腰部）
        m_clothesList.append({
            "运动裤",
            ":/downclothes/materialPackage/downclothes/trousers1.png",
            "下装",
            QPoint(0, 120),
            QPoint(0, 80)      // 对齐腰部
        });
        m_clothesList.append({
            "牛仔裤",
            ":/downclothes/materialPackage/downclothes/trousers2.png",
            "下装",
            QPoint(0, 120),
            QPoint(0, 80)
        });

        // 添加连衣裙（wearOffset：对齐人物全身）
        m_clothesList.append({
            "粉色连衣裙",
            ":/dress/materialPackage/dress/dress1.png",
            "连衣裙",
            QPoint(0, 50),
            QPoint(0, 20)      // 对齐全身
        });
        m_clothesList.append({
            "蓝色连衣裙",
            ":/dress/materialPackage/dress/dress2.png",
            "连衣裙",
            QPoint(0, 50),
            QPoint(0, 20)      // 对齐全身
        });
        m_clothesList.append({
            "中式连衣裙",
            ":/dress/materialPackage/dress/dress3.png",
            "连衣裙",
            QPoint(0, 50),
            QPoint(0, 20)      // 对齐全身
        });

        // 添加鞋子（wearOffset：对齐人物脚部）
        m_clothesList.append({
            "凉鞋",
            ":/shoes/materialPackage/shoes/shoes1.png",
            "鞋子",
            QPoint(0, 300),
            QPoint(0, 220)     // 对齐脚部
        });
        m_clothesList.append({
            "皮鞋",
            ":/shoes/materialPackage/shoes/shoes2.png",
            "鞋子",
            QPoint(0, 300),
            QPoint(0, 220)     // 对齐脚部
        });
        m_clothesList.append({
            "运动鞋",
            ":/shoes/materialPackage/shoes/shoes3.png",
            "鞋子",
            QPoint(0, 300),
            QPoint(0, 220)
        });

    //将服饰添加到对应的列表
    foreach(const ClothesInfo &info, m_clothesList)
    {
        QListWidgetItem *item = new QListWidgetItem;
        QPixmap pixmap(info.path);
        if(pixmap.isNull())
        {
            qWarning() << "Failed to load image:" << info.path;
            item->setIcon(QIcon::fromTheme("image-x-generic"));
        }
        else
        {
            item->setIcon(QIcon(pixmap));
        }
        item->setText(info.name);
        item->setSizeHint(QSize(100, 100));

        if (info.category == "上衣")
            m_upcloList->addItem(item);
        else if (info.category == "下装")
            m_downcloList->addItem(item);
        else if (info.category == "鞋子")
            m_shoesList->addItem(item);
        else if (info.category == "连衣裙")
            m_dressList->addItem(item);
    }
}

void MainWindow::clearCurrentClothes()
{
    //清除上衣
    if (m_upcloItem)
    {
        m_scene->removeItem(m_upcloItem);
        delete m_upcloItem;
        m_upcloItem = nullptr;
    }

    //清除下装
    if (m_downcloItem)
    {
        m_scene->removeItem(m_downcloItem);
        delete m_downcloItem;
        m_downcloItem = nullptr;
    }

    //清除连衣裙
    if (m_dressItem)
    {
        m_scene->removeItem(m_dressItem);
        delete m_dressItem;
        m_dressItem = nullptr;
    }

    //清除鞋子
    if (m_shoesItem)
    {
        m_scene->removeItem(m_shoesItem);
        delete m_shoesItem;
        m_shoesItem = nullptr;
    }
}

void MainWindow::addClothesToScene(const ClothesInfo &info)
{
    hideCombo();
    //先清除同类型的已有服饰
    if (info.category == "上衣")
    {
         if (m_upcloItem)
         {
              m_scene->removeItem(m_upcloItem);
              delete m_upcloItem;
         }
              m_upcloItem = new DragablePixmapItem(info.name); // 传入名称
              m_scene->addItem(m_upcloItem);
              connect(m_upcloItem, &DragablePixmapItem::positionChanged, this, &MainWindow::checkClothesCollision);
    }
    else if (info.category == "下装")
    {
        if (m_downcloItem)
        {
            m_scene->removeItem(m_downcloItem);
            delete m_downcloItem;
        }
        m_downcloItem = new DragablePixmapItem(info.name);
        m_scene->addItem(m_downcloItem);
        connect(m_downcloItem, &DragablePixmapItem::positionChanged, this, &MainWindow::checkClothesCollision);
    }
    else if (info.category == "连衣裙")
    {
        if (m_dressItem)
        {
            m_scene->removeItem(m_dressItem);
            delete m_dressItem;
        }
        m_dressItem = new DragablePixmapItem(info.name);
        m_scene->addItem(m_dressItem);
        connect(m_dressItem, &DragablePixmapItem::positionChanged, this, &MainWindow::checkClothesCollision);
    }
    else if (info.category == "鞋子")
    {
        if (m_shoesItem)
        {
            m_scene->removeItem(m_shoesItem);
            delete m_shoesItem;
        }
        m_shoesItem = new DragablePixmapItem(info.name);
        m_scene->addItem(m_shoesItem);
        connect(m_shoesItem, &DragablePixmapItem::positionChanged, this, &MainWindow::checkClothesCollision);
        checkAndShowCombo();
    }

    //获取当前要显示的服饰项
    DragablePixmapItem* currentItem = nullptr;
    if (info.category == "上衣") currentItem = m_upcloItem;
    else if (info.category == "下装") currentItem = m_downcloItem;
    else if (info.category == "连衣裙") currentItem = m_dressItem;
    else if (info.category == "鞋子") currentItem = m_shoesItem;

    QPixmap pixmap(info.path);
       if (pixmap.isNull())
       {
           qWarning() << "Failed to load clothes image:" << info.path;
           return;
       }
       currentItem->setPixmap(pixmap.scaled(pixmap.size() * m_clothesScale, Qt::KeepAspectRatio, Qt::SmoothTransformation));

       if (currentItem)
          {
              QPixmap pixmap(info.path);
              if(!pixmap.isNull())
              {
                  currentItem->setPixmap(pixmap.scaled(pixmap.size() * m_clothesScale, Qt::KeepAspectRatio, Qt::SmoothTransformation));
              }
              currentItem->setPos(m_scene->sceneRect().center() + info.dragOffset);
          }

       // 设置初始位置（基于人物位置偏移）
       if (m_characterItem)
       {
           QPointF characterPos = m_characterItem->pos();
           currentItem->setPos(characterPos + info.dragOffset); // 临时拖拽位置
       }
       else
       {
           currentItem->setPos(info.dragOffset); // 若人物未加载，使用默认偏移
       }

}

//上衣列表项点击事件处理
void MainWindow::onUpListItemClicked(QListWidgetItem *item)
{
    if(!item)
    {
        return;
    }

    //获取服饰信息
    ClothesInfo info = getClothesInfoByName(item->text());
    if(info.name.isEmpty())
    {
        QMessageBox::warning(this,"错误","找不到选中的服饰信息");
        return;
    }
    //如果当前有连衣裙，先移除
    if(m_dressItem)
    {
        m_scene->removeItem(m_dressItem);
        delete m_dressItem;
        m_dressItem = nullptr;
    }
    //添加到场场景
    addClothesToScene(info);
}

//下装列表项点击事件处理
void MainWindow::onDownListItemClicked(QListWidgetItem *item)
{
    if(!item)
    {
        return;
    }

    //获取服饰信息
    ClothesInfo info = getClothesInfoByName(item->text());
    if(info.name.isEmpty())
    {
        QMessageBox::warning(this,"错误","找不到选中的服饰信息");
        return;
    }
    //如果当前有连衣裙，先移除
    if(m_dressItem)
    {
        m_scene->removeItem(m_dressItem);
        delete m_dressItem;
        m_dressItem = nullptr;
    }
    //添加到场场景
    addClothesToScene(info);
}

//鞋子列表项点击事件处理
void MainWindow::onShoesListItemClicked(QListWidgetItem *item)
{
    if(!item)
    {
        return;
    }

    //获取服饰信息
    ClothesInfo info = getClothesInfoByName(item->text());
    if(info.name.isEmpty())
    {
        QMessageBox::warning(this,"错误","找不到选中的服饰信息");
        return;
    }

    //添加到场场景
    addClothesToScene(info);
}

//连衣裙列表项点击事件处理
void MainWindow::onDressListItemClicked(QListWidgetItem *item)
{
    // 关键修改8：选择连衣裙时隐藏上下装
        if (m_upcloItem)
        {
            m_scene->removeItem(m_upcloItem);
            delete m_upcloItem;
            m_upcloItem = nullptr;
        }
        if (m_downcloItem)
        {
            m_scene->removeItem(m_downcloItem);
            delete m_downcloItem;
            m_downcloItem = nullptr;
        }

        // 加载选中的连衣裙
        ClothesInfo info = getClothesInfoByName(item->text());
        addClothesToScene(info);
}

bool MainWindow::onConfirmBtnClicked()
{
    // 检查是否有完整搭配（上衣+下装+鞋子 或 连衣裙+鞋子）
    bool hasCompleteOutfit = false;
    bool comboFound = false;

    // 检查上衣+下装+鞋子组合
    if (m_upcloItem && m_downcloItem && m_shoesItem)
    {
        hasCompleteOutfit = true;
        comboFound = checkAndShowCombo(); // 修改为返回布尔值
    }
    // 检查连衣裙+鞋子组合
    else if (m_dressItem && m_shoesItem)
    {
        hasCompleteOutfit = true;
        comboFound = checkAndShowCombo(); // 修改为返回布尔值
    }

    if (hasCompleteOutfit)
    {
        checkAndShowCombo();  // 触发合成图显示
        if (comboFound)
        {
          QMessageBox::information(this, "提示", "已生成搭配效果！");
        }
        else
        {
          QMessageBox::information(this, "提示", "搭配完成，但无特殊效果");
        }
      }
    else
    {
        QMessageBox::warning(this, "提示", "请选择完整搭配（上衣+下装+鞋子 或 连衣裙+鞋子）");
    }
     return comboFound;
}

// BGM开关按钮点击槽函数
void MainWindow::onBgmToggleBtnClicked()
{
    toggleBGM();
}

// 音量变化槽函数
void MainWindow::onVolumeChanged(int volume)
{
    setVolume(volume);
}

// 实现辅助函数 getClothesInfoByName
ClothesInfo MainWindow::getClothesInfoByName(const QString &name)
{
    foreach (const ClothesInfo& info, m_clothesList)
    {
        if (info.name == name)
        {
            return info;
        }
    }
    return ClothesInfo(); // 未找到返回空
}

// 根据服饰项获取对应的ClothesInfo（辅助函数）
ClothesInfo MainWindow::getClothesInfoByItem(DragablePixmapItem* item)
{
    if (!item) return ClothesInfo();

     return getClothesInfoByName(item->name());
}


//场景一按钮点击事件处理
void MainWindow::onScene1BtnClicked()
{
    m_currentScene = 1;
    updateBackground(); // 更新为房间背景

}


void MainWindow::onScene2BtnClicked()
{

    m_currentScene = 2;
    updateBackground(); // 更新为教室背景

}

//保存按钮
void MainWindow::onSaveBtnClicked()
{
    //获取场景的截图
    QPixmap pixmap = m_view->grab();

    //弹出文件对话框，让用户选择保存路径
    QString fileName = QFileDialog::getSaveFileName(this,
            tr("保存搭配"), "",
            tr("PNG图片 (*.png);;JPEG图片 (*.jpg *.jpeg);;所有文件 (*)"));

        if (fileName.isEmpty())
        {
            return;
        }

        // 保存图片
        if (!pixmap.save(fileName))
        {
            QMessageBox::warning(this, "保存失败", "无法保存图片文件");
        }
        else
        {
            QMessageBox::information(this, "保存成功", QString("图片已保存到: %1").arg(fileName));
        }
}

//重置按钮点击事件处理
void MainWindow::onResetBtnClicked()
{

    hideCombo(); // 隐藏合成图
    clearCurrentClothes();

        // 关键修改9：重置时重新加载人物（防止被误删）
        if (!m_characterItem)
        {
            loadCharacter();
        }
}

//随机按钮点击事件处理
void MainWindow::onRandomBtnClicked()
{
    //清除当前搭配的服饰
    clearCurrentClothes();

    //获取随机数生成器
    QRandomGenerator* generator = QRandomGenerator::global();

    //随机选择上衣加下装或者连衣裙
    bool chooseDress = (generator->bounded(2) == 0)&&(m_dressList->count()>0);

    if(chooseDress)
    {
        //随机选择连衣裙
        int randomIndex = generator->bounded(m_dressList->count());
        QListWidgetItem *item = m_dressList->item(randomIndex);

        if(item)
        {
            onDressListItemClicked(item);
        }
    }
    else
    {
     // 随机选择上衣（如果有）
      if (m_upcloList->count() > 0)
      {
            int randomIndex = generator->bounded(m_upcloList->count());
             QListWidgetItem *item = m_upcloList->item(randomIndex);
             if (item)
             {
                 onUpListItemClicked(item);
             }


                // 随机选择下装（如果有）
                if (m_downcloList->count() > 0)
                {
                    int randomIndex = generator->bounded(m_downcloList->count());
                    QListWidgetItem *item = m_downcloList->item(randomIndex);
                    if (item)
                    {
                        onDownListItemClicked(item);
                    }
                }
        }
    }
    if (m_shoesList->count() > 0)
        {
            int shoeIndex = generator->bounded(m_shoesList->count());
            QListWidgetItem *shoeItem = m_shoesList->item(shoeIndex);
            if (shoeItem)
            {
                onShoesListItemClicked(shoeItem);
            }
        }
}

//主题切换事件处理
void MainWindow::onThemeCheckBoxToggled(bool checked)
{
    if (checked)
    {
          // 深色主题
            QPalette palette = qApp->palette();
            palette.setColor(QPalette::Window, QColor(53, 53, 53));
            palette.setColor(QPalette::WindowText, Qt::white);
            palette.setColor(QPalette::Base, QColor(25, 25, 25));
            palette.setColor(QPalette::AlternateBase, QColor(53, 53, 53));
            palette.setColor(QPalette::ToolTipBase, Qt::white);
            palette.setColor(QPalette::ToolTipText, Qt::white);
            palette.setColor(QPalette::Text, Qt::white);
            palette.setColor(QPalette::Button, QColor(53, 53, 53));
            palette.setColor(QPalette::ButtonText, Qt::white);
            palette.setColor(QPalette::BrightText, Qt::red);
            palette.setColor(QPalette::Link, QColor(42, 130, 218));
            palette.setColor(QPalette::Highlight, QColor(42, 130, 218));
            palette.setColor(QPalette::HighlightedText, Qt::black);
            qApp->setPalette(palette);
            // 设置视图背景为深色透明
            m_view->setBackgroundBrush(QColor(53, 53, 53, 100)); // 添加透明度
            m_view->setStyleSheet("background: rgba(53, 53, 53, 100);");
    }
    else
    {
        // 浅色主题（默认）
                qApp->setPalette(qApp->style()->standardPalette());

                // 设置视图背景为透明
                m_view->setBackgroundBrush(Qt::transparent);
                m_view->setStyleSheet("background: transparent;");

    }
}
// 加载人物形象到场景
void MainWindow::loadCharacter()
{
    // 先移除现有人物（如果有）
    if (m_characterItem)
    {
        m_scene->removeItem(m_characterItem);
        delete m_characterItem;
        m_characterItem = nullptr;
    }

    // 设置人物资源路径（请替换为实际路径）
    m_characterPath = ":/girl/materialPackage/cartoolgirl.png";

    QPixmap characterPixmap(m_characterPath);
    if (characterPixmap.isNull())
    {
        qWarning() << "Failed to load character image:" << m_characterPath;
        return;
    }

    // 创建人物图形项（不可拖拽）
    if (m_characterItem)
    {
        m_scene->removeItem(m_characterItem);
        delete m_characterItem;
    }
    m_characterItem = new QGraphicsPixmapItem;

    // 根据当前窗口大小计算缩放比例
        QSize windowSize = size();
        qreal scaleFactor = qMin(windowSize.width() / 1000.0, windowSize.height() / 700.0);
        scaleFactor = qBound(0.5, scaleFactor, 2.0);

        QSize scaledSize = characterPixmap.size() * scaleFactor * 0.40;
        m_characterItem->setPixmap(
            characterPixmap.scaled(scaledSize, Qt::KeepAspectRatio, Qt::SmoothTransformation)
        );

        m_scene->addItem(m_characterItem);

        // 居中人物
        centerCharacter();
}

// 检测服饰是否与人物碰撞（在mainwindow.cpp中）
void MainWindow::checkClothesCollision(DragablePixmapItem* clothesItem)
{
    if (!m_characterItem || !clothesItem) return;

    // 如果已经穿戴，不需要重复检测
    if (clothesItem->isWorn()) return;

    // 获取人物和服饰的碰撞区域（场景坐标系）
    QRectF characterRect = m_characterItem->mapRectToScene(m_characterItem->boundingRect());
    QRectF clothesRect = clothesItem->mapRectToScene(clothesItem->boundingRect());

    // 检测碰撞（重叠面积超过服饰面积的30%视为有效穿戴）
    QRectF intersection = characterRect.intersected(clothesRect);
    if (intersection.width()*intersection.height() > clothesRect.width()*clothesRect.height() * 0.3) {
        wearClothes(clothesItem); // 穿戴服饰
    }
}

// 穿戴服饰（自动对齐到人物身上）
void MainWindow::wearClothes(DragablePixmapItem* clothesItem)
{
    if (!clothesItem || m_showingCombo) return;

    clothesItem->setWorn(true);
    clothesItem->setFlag(QGraphicsItem::ItemIsMovable, false); // 穿戴后不可移动

    // 2. 获取该服饰的信息（主要是wearOffset）
    ClothesInfo info = getClothesInfoByItem(clothesItem); // 需实现这个函数
    if (m_characterItem)
        {
            QPointF charPos = m_characterItem->pos();
            clothesItem->setPos(charPos + info.wearOffset);
        }



    // 3. 计算对齐位置（人物位置 + 穿戴偏移）
    QPointF characterPos = m_characterItem->pos();
    QPointF wearPos = characterPos + info.wearOffset;

    // 4. 固定服饰位置并设置层级（在人物上方）
    clothesItem->setPos(wearPos);
    clothesItem->setZValue(1); // 人物z=0，服饰z=1确保显示在上方

    // 5. 穿戴后禁止拖拽（可选，也可以允许微调）
    clothesItem->setFlag(QGraphicsItem::ItemIsMovable, true);
}

// 实现检查并显示套装合成图的函数
bool MainWindow::checkAndShowCombo()
{

        // 严格检查是否有完整搭配（上衣+下装+鞋子 或 连衣裙+鞋子）
        bool hasCompleteOutfit = false;
        if ((m_upcloItem && m_upcloItem->isWorn() &&
             m_downcloItem && m_downcloItem->isWorn() &&
             m_shoesItem && m_shoesItem->isWorn()) ||
            (m_dressItem && m_dressItem->isWorn() &&
             m_shoesItem && m_shoesItem->isWorn())) {
            hasCompleteOutfit = true;
        }

        // 如果没有完整搭配，直接返回（不显示合成图）
        if (!hasCompleteOutfit) {
            qDebug() << "搭配不完整，不显示合成图";
            return false;
        }

        // 获取当前穿戴的服饰名称
        QString topName = m_upcloItem ? getClothesInfoByItem(m_upcloItem).name : "";
        QString dressName = m_dressItem ? getClothesInfoByItem(m_dressItem).name : "";
        QString bottomName = m_downcloItem ? getClothesInfoByItem(m_downcloItem).name : "";
        QString shoesName = m_shoesItem ? getClothesInfoByItem(m_shoesItem).name : "";

        qDebug() << "当前选择 - 上衣:" << topName << "连衣裙:" << dressName << "下装:" << bottomName << "鞋子:" << shoesName;

        // 遍历所有套装查找匹配
        foreach (const OutfitCombo &combo, m_outfitCombos)
        {
            qDebug() << "检查套装:" << combo.name
                     << "要求 - 上衣:" << combo.top
                     << "连衣裙:" << combo.dress
                     << "下装:" << combo.bottom
                     << "鞋子:" << combo.shoes;

            // 匹配上衣+下装+鞋子组合（非连衣裙套装）
            if (!combo.top.isEmpty() && combo.dress.isEmpty())
            {
                if (combo.top == topName && combo.bottom == bottomName && combo.shoes == shoesName)
                {
                    return showComboImage(combo.comboImagePath);
                }
            }
            // 匹配连衣裙+鞋子组合（连衣裙套装）
            else if (combo.top.isEmpty() && !combo.dress.isEmpty())
            {
                if (combo.dress == dressName && combo.shoes == shoesName)
                {
                    return showComboImage(combo.comboImagePath);
                }
            }
        }

        // 没有找到匹配的套装
        qDebug() << "未找到匹配的套装组合";
        return false;
   }


bool MainWindow::showComboImage(const QString &imagePath)
{
    QPixmap pixmap(imagePath);
    if (pixmap.isNull())
    {
        qWarning() << "无法加载合成图，路径错误:" << imagePath;
        return false;
    }

    // 显示合成图
    if (m_comboItem)
    {
        m_scene->removeItem(m_comboItem);
        delete m_comboItem;
    }

    m_comboItem = new QGraphicsPixmapItem;

    // 根据当前窗口大小计算缩放比例
    QSize windowSize = size();
    qreal scaleFactor = qMin(windowSize.width() / 1000.0, windowSize.height() / 700.0);
    scaleFactor = qBound(0.5, scaleFactor, 2.0);

     // 使用与人物相同的缩放逻辑
     QSize scaledSize = pixmap.size() * scaleFactor * 0.25;
     m_comboItem->setPixmap(pixmap.scaled(scaledSize, Qt::KeepAspectRatio, Qt::SmoothTransformation));
     m_comboItem->setPos(m_characterItem->pos());
     m_scene->addItem(m_comboItem);

      // 保存当前合成图路径，用于后续缩放调整
      m_currentComboPath = imagePath;


    // 隐藏原始元素
    if (m_characterItem) m_characterItem->hide();
    if (m_upcloItem) m_upcloItem->hide();
    if (m_downcloItem) m_downcloItem->hide();
    if (m_dressItem) m_dressItem->hide();
    if (m_shoesItem) m_shoesItem->hide();

    m_showingCombo = true;
    return true;
}
// 实现隐藏合成图的函数
void MainWindow::hideCombo()
{
    if (!m_showingCombo) return;

    // 移除合成图
    if (m_comboItem)
    {
        m_scene->removeItem(m_comboItem);
        delete m_comboItem;
        m_comboItem = nullptr;
    }

    // 显示原始元素
    if (m_characterItem) m_characterItem->show();
    if (m_upcloItem) m_upcloItem->show();
    if (m_downcloItem) m_downcloItem->show();
    if (m_dressItem) m_dressItem->show();
    if (m_shoesItem) m_shoesItem->show();

    m_showingCombo = false;
}

void MainWindow::loadOutfitCombos()
{
    // 添加套装组合，根据实际资源路径修改
    m_outfitCombos.append({
        "休闲套装",
        "白色T恤","","牛仔裤", "凉鞋",
        ":/combined/materialPackage/combined/T1_t2_s1.png"
    });
    // 如果需要连衣裙套装，可以这样定义
    m_outfitCombos.append({
        "连衣裙套装",
        "",           // top: 为空
        "粉色连衣裙",  // dress: 连衣裙名称
        "",           // bottom: 为空
        "凉鞋",       // shoes: 鞋子名称
        ":/combined/materialPackage/combined/d1_s1.png"
    });
    m_outfitCombos.append({
        "连衣裙套装2",
        "",           // top: 为空
        "蓝色连衣裙",  // dress: 连衣裙名称
        "",           // bottom: 为空
        "凉鞋",       // shoes: 鞋子名称
        ":/combined/materialPackage/combined/d2_s1.png"
    });
    m_outfitCombos.append({
        "连衣裙套装3",
        "",           // top: 为空
        "中式连衣裙",  // dress: 连衣裙名称
        "",           // bottom: 为空
        "皮鞋",       // shoes: 鞋子名称
        ":/combined/materialPackage/combined/d3_s2.png"
    });

    // 添加套装组合，根据实际资源路径修改
    m_outfitCombos.append({
        "运动套装",
        "蓝色T恤","","运动裤", "运动鞋",
        ":/combined/materialPackage/combined/T2_t1_s3.png"
    });

    // 添加套装组合，根据实际资源路径修改
    m_outfitCombos.append({
        "牛仔套装",
        "牛仔外套","","牛仔裤", "皮鞋",
        ":/combined/materialPackage/combined/ja_t2_s2.png"
    });
    // 添加套装组合，根据实际资源路径修改
    m_outfitCombos.append({
        "一身蓝套装",
        "蓝色T恤","","牛仔裤", "皮鞋",
        ":/combined/materialPackage/combined/T2_t2_s2.png"
    });
    // 添加套装组合，根据实际资源路径修改
    m_outfitCombos.append({
        "芬兰套装",
        "粉色T恤","","牛仔裤", "皮鞋",
        ":/combined/materialPackage/combined/T3_t2_s2.png"
    });
    // 添加套装组合，根据实际资源路径修改
    m_outfitCombos.append({
        "阳光套装",
        "黄色T恤","","运动裤", "凉鞋",
        ":/combined/materialPackage/combined/T4_t1_s1.png"
    });
    // 添加套装组合，根据实际资源路径修改
    m_outfitCombos.append({
        "阳光运动",
        "黄色T恤","","运动裤", "运动鞋",
        ":/combined/materialPackage/combined/T4_t1_s3.png"
    });


}
